import React, { PureComponent, Fragment } from 'react';
import {
  Drawer,
  Col,
  Row,
  Tabs, Button, Icon, Modal, message,
} from 'antd';
import { connect } from 'dva';
import groupBy from 'lodash/groupBy';
import forEach from 'lodash/forEach';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
import styles from './../ValveFlowMeterSite/index.less';
import gold_groud from './../../images/valve_small.png';
import gold_groud2 from './../../images/valve2_small.jpg';
import unknow from './../../images/unknow.png';
import ConstructionDate from './ConstructionDate';
import { afterCloseModal } from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import request from '@/utils/request';
import moment from 'moment';
import liuliangji from '@/images/liuliangji.png';
import shuizhi from '@/images/shuizhi.png';
import dcjlq from '@/images/dcjlq.jpg';
import DN800SNLD from '@/images/DN800SNLD.jpg';
import DN800unknow from '@/images/DN800unknow.jpg';
import LDE from '@/images/LDE.jpg';
import shuiweiji from '@/images/shuiweiji.png';
import DN300sf from '@/images/DN300sf.jpg';
import temp11 from '@/images/temp11.png';
import temp12 from '@/images/temp12.png';
import Street from '@/pages/Pipe_home/Street';

const { TabPane } = Tabs;

@connect(({ devices, loading }) => ({
  devices,
}))
class BasicList extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      group: {},
      groupNameMap: {
        'press_sensor': '压力传感器',
        'pipe': '现状管道',
        'water': '水厂监控设备',
        'workstations1': '双阀减压阀井',
        'appendage': '附属物',
        'characteristic': '特征',
      },
      pipe_construction_date:{},
      pipe_street:{},
    };
  }


  componentDidMount() {
    const that = this;
    const group = groupBy(this.props.selectFeature, 'ground_set');
    console.log('group', group);
    this.setState({
      group,
    });
    request(`/guest/annotations/pipe_construction_date`, {
      method: 'get',
    }).then((response) => {
      if (response.status === 200) {
        if (response.data.data.value) {
          console.log('有value')
          that.setState({
            pipe_construction_date: response.data.data.value,
          });
        } else {
          console.log('无value')
        }

      }
    });
    request(`/guest/annotations/pipe_street`, {
      method: 'get',
    }).then((response) => {
      if (response.status === 200) {
        if (response.data.data.value) {
          console.log('有value')
          that.setState({
            pipe_street: response.data.data.value,
          });
        } else {
          console.log('无value')
        }

      }
    });

  }

  componentWillUnmount() {
  }

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'check-circle', color = '#004cff', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  exportPipe=()=>{
    console.log('group[key]',this.state.group['pipe'])
    console.log(XLSX)
    const XLSX=window.XLSX
    // 从头开始创建工作簿
    var wb = XLSX.utils.book_new();
    /**
     * 创建工作表
     * aoa_to_sheet    二维数组
     * json_to_sheet   对象数组
     * table_to_sheet  tableDOM
     */
    const group=this.state.group['pipe']
    let data=[]
    for(let i=0;i<group.length;i++){
      data.push({
        "id":group[i].id,
        "sid":group[i].sid,
        "起点":group[i].coordinates[0][0].toString(),
        "终点":group[i].coordinates[0][1].toString(),
        "埋设方式":group[i].埋设方式,
        "材质":group[i].材质,
        "管径":group[i].管径,
        "线型":group[i].线型,
        "起点埋深":group[i].起点埋深,
        "终点埋深":group[i].终点埋深,
        "长度":group[i].长度,
      })
    }
    let ws= XLSX.utils.json_to_sheet(data);
    // 把工作表添加到工作簿中
    XLSX.utils.book_append_sheet(wb, ws, "sheet");
    XLSX.writeFile(wb,"gis.xlsx");
  };
  renderTabPane = (group) => {
    const that = this;
    const defaultColumnProperties = {
      resizable: true,
    };
    const defaultColumnProperties2 = {
      resizable: true,
      sortable: true,
    };
    const columns = [
      {
        name: '压力传感器名称',
        width: 190,
        key: 'name',

      },
      {
        name: 'IMEI',
        key: 'imei',
        width: 130,
      },
      {
        name: '安装地址',
        width: 150,
        key: 'address',
      },
      {
        name: '在线状态',
        key: 'online_status',
        width: 80,
        formatter: (event) => {
          return this.renderStatus(event.value);
        },
      },
      {
        name: '创建时间',
        width: 150,
        key: 'created_at',
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              this.props.showDetail(event.row);
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    const pipeColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: 'ID',
        width: 80,
        key: 'id',
        sortDescendingFirst: true,

      },
      {
        name: 'SID',
        width: 120,
        key: 'sid',

      },
      {
        name: '起点埋深(m)',
        key: '起点埋深',
        width: 100,
      },
      {
        name: '终点埋深(m)',
        key: '终点埋深',
        width: 100,
      },
      {
        name: '材质',
        key: '材质',
        width: 90,
        sortDescendingFirst: true,
      },
      {
        name: '埋设方式',
        key: '埋设方式',
        width: 95,
      },
      {
        name: '线型',
        key: '线型',
        width: 100,
      },
      {
        name: '管径',
        key: '管径',
        width: 85,
        sortDescendingFirst: true,
      },
      {
        name: '长度(m)',
        key: '长度',
        width: 100,
        formatter: (event) => <Fragment>
          {event.value.toFixed(2)}
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties2, ...c }));
    const appendageCharcColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '管点编号',
        width: 80,
        key: '管点编号',
        sortDescendingFirst: true,
      },
      {
        name: '附属物',
        key: '附属物',
        width: 100,
      },
      {
        name: '特征',
        key: '特征',
        width: 100,
      },

      {
        name: '地面高程',
        key: '地面高程',
        width: 90,
      },
      {
        name: '井底埋深',
        key: '井底埋深',
        width: 95,
      },
      {
        name: '井盖类型',
        key: '井盖类型',
        width: 100,
      },
      {
        name: '井盖材质',
        key: '井盖材质',
        width: 85,
      },
      {
        name: '精度级别',
        key: '精度级别',
        width: 85,
      },
      {
        name: '备注',
        key: '备注',
        width: 85,
      },
    ].map(c => ({ ...defaultColumnProperties2, ...c }));

    let result = [];
    for (let key  in group) {
      if (key === 'press_sensor') {
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => group[key][i]}
              rowsCount={group[key].length}
              minHeight={400}

            />
          </TabPane>,
        );
      } else if (key === 'pipe') {
        let totalLength = 0;
        for (let i = 0; i < group[key].length; i++) {
          totalLength += Number(group[key][i]['长度']);
        }
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>

            <h3 style={{
              float: 'right',
              overflow: 'hidden',
              marginBottom: '5px',
              marginRight: '5px',
              color: 'blue', cursor: 'pointer',
            }} onClick={() => {
              this.setState({
                constructionDateModal: true,
              });
            }}>批量设置管道建设日期</h3>
            <h3 style={{
              float: 'right',
              overflow: 'hidden',
              marginBottom: '5px',
              marginRight: '15px',
              color: 'blue', cursor: 'pointer',
            }} onClick={() => {
              this.setState({
                streetModal: true,
              });
            }}>批量设置管道所在街道</h3>
            <ReactDataGrid
              columns={pipeColumns}
              rowGetter={i => {
                return { ...group[key][i], _index: i };
              }}
              rowsCount={group[key].length}
              minHeight={400}
              onGridSort={(sortColumn, sortDirection) => {
                const comparer = (a, b) => {
                  if (sortDirection === 'ASC') {
                    return a[sortColumn] > b[sortColumn] ? 1 : -1;
                  } else if (sortDirection === 'DESC') {
                    return a[sortColumn] < b[sortColumn] ? 1 : -1;
                  }
                };
                const parseData = sortDirection === 'NONE' ? group[key] : [...group[key]].sort(comparer);
                that.setState({
                  group: {
                    ...that.state.group,
                    pipe: parseData,
                  },
                });
              }

              }
            />
            <h2 style={{
              float: 'right',
              overflow: 'hidden',
              marginTop: '5px',
              marginBottom: '0',
              marginRight: '5px',
            }}>管道总长度: {totalLength.toFixed(2)} 米 <Button type={'primary'} onClick={this.exportPipe}>导出当前数据</Button></h2>
          </TabPane>,
        );
      } else if (key === 'appendage' || key === 'characteristic') {
        let totalLength = 0;
        for (let i = 0; i < group[key].length; i++) {
          totalLength += Number(group[key][i]['长度']);
        }
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={appendageCharcColumns}
              rowGetter={i => {
                return { ...group[key][i], _index: i };
              }}
              rowsCount={group[key].length}
              minHeight={436}
              onGridSort={(sortColumn, sortDirection) => {
                const comparer = (a, b) => {
                  if (sortDirection === 'ASC') {
                    return a[sortColumn] > b[sortColumn] ? 1 : -1;
                  } else if (sortDirection === 'DESC') {
                    return a[sortColumn] < b[sortColumn] ? 1 : -1;
                  }
                };
                const parseData = sortDirection === 'NONE' ? group[key] : [...group[key]].sort(comparer);
                that.setState({
                  group: {
                    ...that.state.group,
                    appendage: parseData,
                  },
                });
              }

              }
            />
          </TabPane>,
        );
      } else if (key === 'water') {
        console.log('group[key]', group[key]);
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}</span>} key={key}>
            <div style={{ minHeight: '400px' }}>
              <Row gutter={16}>
                {
                  group[key].map((item, index) => {
                    if (item.item1) {
                      return <Col span={8} key={index}>
                        <h3 style={{ marginTop: '5px', fontWeight: 'bold' }}>园艺场沉沙池
                          <span
                            onClick={() => this.props.showWaterDetail('园艺场沉沙池')}
                            style={{ cursor: 'pointer', fontSize: '12px', float: 'right', marginTop: '3px' }}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2">
                          <div className="item">
                            <li>液位(m)</li>
                            <li>浊度(NTU)</li>
                          </div>
                          <div className="item2">
                            <li>{item.item1}</li>
                            <li>{item.item2}</li>
                          </div>
                        </div>
                      </Col>;
                    } else if (item.item3) {
                      return <Col span={8} key={index}>
                        <h3 style={{ marginTop: '5px', fontWeight: 'bold' }}>塔尔郎水厂
                          <span
                            onClick={() => this.props.showWaterDetail('塔尔郎水厂')}
                            style={{ cursor: 'pointer', fontSize: '12px', float: 'right', marginTop: '3px' }}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2">
                          <div className="item">
                            <li>进水流量(m³/h)</li>
                            <li>出水流量(m³/h)</li>
                            <li>取水口浊度(NTU)</li>
                          </div>
                          <div className="item2">
                            <li>{item.item3}</li>
                            <li>{item.item4}</li>
                            <li>{item.item5}</li>
                          </div>
                        </div>
                      </Col>;
                    } else if (item.item6) {
                      return <Col span={8} key={index}>
                        <h3 style={{ marginTop: '5px', fontWeight: 'bold' }}>老城区水厂
                          <span
                            onClick={() => this.props.showWaterDetail('老城区水厂')}
                            style={{ cursor: 'pointer', fontSize: '12px', float: 'right', marginTop: '3px' }}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2">
                          <div className="item">
                            <li>出水流量(m³/h)</li>
                            <li>1#液位(m)</li>
                            <li>2#/3#液位(m)</li>

                          </div>
                          <div className="item2">
                            <li>{item.item8}</li>
                            <li>{item.item7}</li>
                            <li>{item.item6}</li>
                          </div>
                        </div>
                      </Col>;
                    } else if (item.item9) {
                      return <Col span={8} key={index}>
                        <h3 style={{ marginTop: '5px', fontWeight: 'bold' }}>示范区水厂
                          <span
                            onClick={() => this.props.showWaterDetail('示范区水厂')}
                            style={{ cursor: 'pointer', fontSize: '12px', float: 'right', marginTop: '3px' }}>
                            查看详情
                          </span>
                        </h3>
                        <div className="pop-content pop-content2">
                          <div className="item">
                            <li>出水流量(m³/h)</li>
                            <li>液位(m)</li>
                          </div>
                          <div className="item2">
                            <li>{item.item10}</li>
                            <li>{item.item9}</li>
                          </div>
                        </div>
                      </Col>;
                    }
                  })
                }
              </Row>
            </div>
          </TabPane>,
        );
      } else if (key === 'workstations1') {
        console.log('group[key]', group[key]);
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}</span>} key={key}>
            <Row className={'img-data-content'} gutter={[16, 16]}
                 style={{ height: '400px', maxHeight: '400px', overflow: 'auto', overflowX: 'hidden' }}>
              {
                group[key].map((item, index) => {
                  let borderTopColor = '#5e83bf';
                  switch (index % 4) {
                    case 0:
                      borderTopColor = '#e77338';
                      break;
                    case 1:
                      borderTopColor = '#5e83bf';
                      break;
                    case 2:
                      borderTopColor = '#31b77d';
                      break;
                    case 3:
                      borderTopColor = '#C790E1';
                      break;

                  }
                  let statusText = '';
                  if (item.online_status === 1) {
                    statusText = <span style={{ background: '#00b209', padding: '1px 4px', color: '#fff' }}>在线</span>;
                  } else if (item.online_status === -1) {
                    statusText = <span style={{ background: 'red', padding: '1px 4px', color: '#fff' }}>离线</span>;
                  }
                  let alarmText = '';
                  if (item.alarm === 0) {
                    alarmText = <span style={{ background: '#00b209', padding: '1px 4px', color: '#fff' }}>无报警</span>;
                  } else if (item.online_status === 1) {
                    alarmText = <span style={{ background: 'red', padding: '1px 4px', color: '#fff' }}>报警</span>;
                  }
                  let template = '未知';
                  if (item.template === 1) {
                    template = '双蝶阀站点';
                  } else if (item.template === 2) {
                    template = '流量计站点';
                  } else if (item.template === 3) {
                    template = '水质检测站点';
                  } else if (item.template === 4) {
                    template = '电磁计量器站点';
                  } else if (item.template === 5) {
                    template = 'DN800电磁流量计(SNLD-DN800)';
                  } else if (item.template === 6) {
                    template = 'DN800电磁流量计(未知)';
                  } else if (item.template === 7) {
                    template = 'LDE-DN400-400(珠华)';
                  } else if (item.template === 8) {
                    template = 'JEER雷达水位计';
                  } else if (item.template === 9) {
                    template = '双阀减压阀站点';
                  } else if (item.template === 10) {
                    template = '宋峰流量计';
                  } else if (item.template === 11) {
                    template = '电磁流量计&压力计';
                  } else if (item.template === 12) {
                    template = '双压力监测点';
                  }
                  let locationImage = unknow;
                  if (item.template === 1) {
                    locationImage = gold_groud2;
                  } else if (item.template === 2) {
                    locationImage = liuliangji;
                  } else if (item.template === 3) {
                    locationImage = shuizhi;
                  } else if (item.template === 4) {
                    locationImage = dcjlq;
                  } else if (item.template === 5) {
                    locationImage = DN800SNLD;
                  } else if (item.template === 6) {
                    locationImage = DN800unknow;
                  } else if (item.template === 7) {
                    locationImage = LDE;
                  } else if (item.template === 8) {
                    locationImage = shuiweiji;
                  } else if (item.template === 9) {
                    locationImage = gold_groud2;
                  } else if (item.template === 10) {
                    locationImage = DN300sf;
                  } else if (item.template === 11) {
                    locationImage = temp11;
                  } else if (item.template === 12) {
                    locationImage = temp12;
                  }
                  return <Col className="gutter-row" md={6} lg={6} xl={6} xxl={4} key={index}>
                    <div className={styles.img_box} style={{
                      border: '1px solid #ccc', padding: '5px', borderTopColor: borderTopColor,
                    }}>
                      <img style={{ cursor: 'pointer' }} onClick={() => {
                        that.props.showWorkstationDetail(item);
                      }} src={locationImage} alt=""/>
                      <h4>站点名称 : {item.name}</h4>
                      <h4 title={`站点IMEI :  ${item.imei}`}>站点IMEI : {item.imei}</h4>
                      <h4>在线状态 : {statusText}</h4>
                      <h4>是否报警 : {alarmText}</h4>
                      <div className={styles.card_type}>
                        {template}
                      </div>
                    </div>
                  </Col>;
                })
              }
            </Row>

          </TabPane>,
        );
      }

    }
    return result;
  };
  handleEditDate = () => {
    const that = this;
    const formValues = this.DateForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    console.log(this.state.group.pipe);
    const pipe_construction_date = this.state.pipe_construction_date;
    let sendData=pipe_construction_date
    console.log('sendData',sendData)
    for (let i = 0; i < this.state.group.pipe.length; i++) {
      sendData[`pipe${this.state.group.pipe[i].id}`]= formValues.date ? moment(formValues.date).format('YYYY-MM-DD') : ''

    }
    console.log('sendDta',sendData)
    request(`/annotations`, {
      method: 'POST',
      data: {
        key: 'pipe_construction_date',
        value: sendData,
        group: 'pipe_construction_date',
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success('操作成功');
        that.setState({
          constructionDateModal: false,
        });
      }
    });
  };
  handleEditPipeStreet = () => {
    const that = this;
    const formValues = this.PipeStreetForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    console.log(this.state.group.pipe);
    const pipe_street = this.state.pipe_street;
    let sendData=pipe_street
    console.log('sendData',sendData)
    for (let i = 0; i < this.state.group.pipe.length; i++) {
      sendData[`street${this.state.group.pipe[i].id}`]= formValues.street ? formValues.street : ''

    }
    console.log('sendDta',sendData)
    request(`/annotations`, {
      method: 'POST',
      data: {
        key: 'pipe_street',
        value: sendData,
        group: 'pipe_street',
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success('操作成功');
        that.setState({
          streetModal: false,
        });

        that.props.renderPipe()
      }
    });
  };

  render() {
    const { dispatch } = this.props;
    return <div>
      <Tabs type="card">
        {
          this.renderTabPane(this.state.group)
        }
      </Tabs>
      <Modal
        title={<BuildModalTitle visible={this.state.constructionDateModal} modalClass="constructionDateModal"
                                title={`批量设置管道建设日期`}/>}
        destroyOnClose
        onCancel={() => {
          this.setState({
            constructionDateModal: false,
          });
        }}
        centered
        className="constructionDateModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        visible={this.state.constructionDateModal}
        onOk={this.handleEditDate}
      >
        <ConstructionDate
          wrappedComponentRef={(inst) => this.DateForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.streetModal} modalClass="streetModal"
                                title={`批量设置管道所在街道`}/>}
        destroyOnClose
        onCancel={() => {
          this.setState({
            streetModal: false,
          });
        }}
        centered
        className="streetModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        visible={this.state.streetModal}
        onOk={this.handleEditPipeStreet}
      >
        <Street street={this.state.street}
                wrappedComponentRef={(inst) => this.PipeStreetForm = inst}/>

      </Modal>
    </div>;
  }
}

export default BasicList;
